#!/bin/python3

import numpy as np
import argparse

parser = argparse.ArgumentParser(description='Calculation of Corp Analysis Report')
parser.add_argument('-t','--target', type=str, default = '000001',help='the object code of corp target.')
args = parser.parse_args()
print('target:' ,args.target)

data_rev = 0x000108
invest_target = '../data/'+args.target

with open(invest_target + '.md','r') as datafile:
    data_version = datafile.readline()
    if 'data_version' in data_version.split(':')[0]:
        data_rev = (int)(data_version.split(':')[1],16)
        skip_rows = data_rev&0xff

print('data version:0x%x' % data_rev)
data = np.loadtxt(invest_target+'.md',comments='#',delimiter='|',skiprows=skip_rows)
rate = np.zeros((data.shape[0],8))

np.set_printoptions(precision=2,suppress=True)
# Date|income|net_margin|total_assets|net_assets|cashin|net_cashin
#
# rate_equity_multiplier|rate_net_margin|rate_asset_turnover|rate_asset_margin|
#   rate_equity_margin|rate_cash_income|rate_cash_margin|
year = 0
for row in data:
    rate[year,0] = row[0]
    rate[year,1] = row[3]/row[4] 
    rate[year,2] = row[2]/row[1]
    rate[year,3] = row[1]/row[3]
    rate[year,4] = row[2]/row[3]
    rate[year,5] = row[2]/row[4]
    rate[year,6] = row[5]/row[1]
    rate[year,7] = row[6]/row[2]
    year += 1
    
print(rate[:])
#result = np.hstack((data,rate[:,1:]))
#print(result)

data_rev = (data_rev & 0xffff00 ) | 0x03 # rate skip rows is 3 lines.
with open(invest_target + '_rate.md','w') as outfile:
    outfile.write('- data_version:' + hex(data_rev)+'\n')
    outfile.write('Date|'
                  'rate_equity_multiplier|rate_net_margin|rate_asset_turnover|rate_asset_margin|'
                  'rate_equity_margin|rate_cash_income|rate_cash_margin|\n'
                  '-----|---|------|-----|-----|----|----|----|\n')
    #np.savetxt(outfile,result,fmt='%.2f',delimiter='|')
    
with open(invest_target + '_rate.md','ab') as outfile:
    np.savetxt(outfile,rate,fmt='%.2f',delimiter='|')

print('Target [',args.target,'] Rate Calc Done.')

